package utils

import (
	"crypto/md5"
	"encoding/hex"
	"github.com/go-playground/validator/v10"
	"gvb_server/api/images_api/strategy"
	"gvb_server/global"
	"gvb_server/models/ctype"
	"mime/multipart"
	"reflect"
)

var uploadStrategy strategy.UploadStrategy

// StringInSlice 判断字符串是否在数组中
func StringInSlice(a string, list []string) bool {
	for _, b := range list {
		if b == a {
			return true
		}
	}
	return false
}

// Md5 获取md5
func Md5(src []byte) string {
	m := md5.New()
	m.Write(src)
	res := hex.EncodeToString(m.Sum(nil))
	return res
}

// GetValidMsg 获取验证错误的提示信息
func GetValidMsg(err error, obj any) string {
	// 需要传递obj的指针
	getObj := reflect.TypeOf(obj)
	// 将err接口断言为具体的类型
	if errs, ok := err.(validator.ValidationErrors); ok {
		// 断言成功
		for _, e := range errs {
			if f, exits := getObj.Elem().FieldByName(e.Field()); exits {
				msg := f.Tag.Get("msg")
				return msg
			}
		}
	}
	return err.Error()
}

func Upload(file *multipart.FileHeader) (filePath string, err error) {
	storage := global.Config.System.Storage
	switch storage {
	case ctype.LOCAL:
		uploadStrategy = new(strategy.LocalUploadStrategy)
		break
	case ctype.QINIU:
		uploadStrategy = new(strategy.QiNiuUploadStrategy)
		break
	}
	return uploadStrategy.Upload(file)
}
